package de.koller.worlders.render.util;

import de.koller.oceanFramework.gl.util.ParticleTexture;
import de.koller.worlders.engine.util.BufferCollection;
import java.awt.image.BufferedImage;
import java.util.Objects;
import org.lwjgl.opengl.GL11;

public class TextureRep {
	
	public final TextureValue texture;
	public final int sx;
	public final int sy;
	public final int sw;
	public final int sh;

	private int color;
	
	public TextureRep( TextureValue texture, int sx, int sy, int sw, int sh ) {
		this.texture = texture;
		this.sx = sx;
		this.sy = sy;
		this.sw = sw;
		this.sh = sh;
		
		this.color = 0;
	}

	public TextureRep( int color ) {
		this( TextureValue.None, 0, 0, 0, 0 );
		this.color = color;
	} 
	
	public ParticleTexture generate( BufferCollection buffer ) {
		if( buffer.getBuffer().containsKey( this ) )
			return buffer.getBuffer().get( this );
		
		if( texture == TextureValue.None )
			return generateOneColor( buffer );
		
		BufferedImage tv = null;
		if( texture == TextureValue.Tiles )
			tv = buffer.tiles;
		
		ParticleTexture.MAG_FILTER = GL11.GL_LINEAR;
		ParticleTexture.MIN_FILTER = GL11.GL_LINEAR;
		ParticleTexture t = ParticleTexture.generate( sw, sh );
		for( int x = sx; x < sx+sw; x++ )
			for( int y = sy; y < sy+sh; y++ )
				t.setPixel( tv.getRGB( x, y ), x-sx, y-sy );
		t.flush();
		
		buffer.getBuffer().put( this, t );
		return t;
	}
	
	private ParticleTexture generateOneColor( BufferCollection buffer ) {
		if( buffer.getBuffer().containsKey( this ) )
			return buffer.getBuffer().get( this );
		
		ParticleTexture.MAG_FILTER = GL11.GL_LINEAR;
		ParticleTexture.MIN_FILTER = GL11.GL_LINEAR;
		ParticleTexture t = ParticleTexture.generate( 4, 4 );
		t.clear( color );
		t.flush();
		buffer.getBuffer().put( this, t );
		return t;
	}
	
	@Override
	public String toString() {
		return "TextureRep{" + "texture=" + texture + ", sx=" + sx + ", sy=" + sy + ", sw=" + sw + ", sh=" + sh + '}';
	}

	@Override
	public boolean equals( Object obj ) {
		if( obj == null ) {
			return false;
		}
		if( getClass() != obj.getClass() ) {
			return false;
		}
		final TextureRep other = ( TextureRep ) obj;
		if( !Objects.equals( this.texture, other.texture ) ) {
			return false;
		}
		if( this.sx != other.sx ) {
			return false;
		}
		if( this.sy != other.sy ) {
			return false;
		}
		if( this.sw != other.sw ) {
			return false;
		}
		if( this.sh != other.sh ) {
			return false;
		}
		if( this.color != other.color ) {
			return false;
		}
		return true;
	}

	@Override
	public int hashCode() {
		int hash = 3;
		hash = 97 * hash + Objects.hashCode( this.texture );
		hash = 97 * hash + this.sx;
		hash = 97 * hash + this.sy;
		hash = 97 * hash + this.sw;
		hash = 97 * hash + this.sh;
		hash = 97 * hash + this.color;
		return hash;
	}
	
	public static enum TextureValue {
		None, Tiles;
	}

	public int getColor() {
		return color;
	}
	
}
